package banner

import (
	"context"
	// "fmt"
	"strconv"
	"strings"
	"time"

	"mall/common/globalkey"
	"mall/common/modelx"
	"mall/common/resultx"
	"mall/common/utils/pointy"
	"mall/service/backend/model"
	"mall/service/backend/rpc/internal/svc"
	"mall/service/backend/rpc/internal/utils/errorhandler"
	"mall/service/backend/rpc/types/backend"

	// "github.com/sirupsen/logrus"
	"github.com/zeromicro/go-zero/core/logx"
)

type GetBannerListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewGetBannerListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetBannerListLogic {
	return &GetBannerListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *GetBannerListLogic) GetBannerList(in *backend.BaseListReq) (*backend.BannerListResp, error) {
	// logrus.Info(fmt.Sprintf("GetBannerList BaseListReq: %+v", in))
	// Limit:10 Preload:"banner:Id,Title,LinkUrl,PicUrl" Filter:"Status,equalTo:1;Type,equalTo:1" VisitorId:0 PlatformId:1

	if in.Filter == nil || len(*in.Filter) == 0 {
		return nil, resultx.StatusError(resultx.REUQEST_PARAM_ERROR, "")
	}

	preloadMap, eagerLoadMap := modelx.ParsePreloadAndEagerLoad(in.Preload, in.EagerLoad)
	// logrus.Info(fmt.Sprintf("GetBannerList preloadMap: %+v", preloadMap))
	// map[banner:[Id Title LinkUrl PicUrl]]
	// logrus.Info(fmt.Sprintf("GetBannerList eagerLoadMap: %+v", eagerLoadMap))
	// map[]

	bannerEntityName := model.RpcEntityNames.Banner
	if _, ok := model.RpcEntityPreloadMap[bannerEntityName]; !ok {
		return &backend.BannerListResp{}, nil
	}

	bannerRepositoryName := model.RepositoryNames.Banner
	columnMap, ok := model.RepositoryPreloadMap[bannerRepositoryName]
	if !ok {
		return &backend.BannerListResp{}, nil
	}

	var selectCols []string
	if preloadFields, ok := preloadMap[bannerEntityName]; ok {
		selectCols = modelx.ParseSelectColumns(preloadFields, columnMap)
	}

	filterMap := modelx.ParseFilter(in.Filter, columnMap)
	// logrus.Info(fmt.Sprintf("GetBannerList filterMap: %+v", filterMap))
	// map[status:map[equalTo:[1]] type:map[equalTo:[1]]]
	if filterMap == nil {
		return nil, resultx.StatusError(resultx.REUQEST_PARAM_ERROR, "")
	}

	now := time.Now()
	filterMap[model.BannerColumns.StartedAt] = map[string][]any{
		"lessThanOrEqualTo": {now},
	}
	filterMap[model.BannerColumns.EndedAt] = map[string][]any{
		"moreThan": {now},
	}

	orderBy := modelx.ParseSorter(in.Sorter, columnMap)
	// logrus.Info(fmt.Sprintf("GetBannerList orderBy: %s", orderBy))
	//
	res, count, err := l.svcCtx.Banner.GetList(l.ctx, model.M{
		"offset":  in.Offset,
		"limit":   in.Limit,
		"orderBy": orderBy,
		"select":  strings.Join(selectCols, ","),
	}, 2, filterMap)
	if err != nil {
		return nil, errorhandler.DefaultRepositoryError(l.Logger, err, in)
	}

	hasNextPage, hasPreviousPage := modelx.ParseCount(count)
	resp := &backend.BannerListResp{
		HasNextPage:     &hasNextPage,
		HasPreviousPage: &hasPreviousPage,
	}

	var total int64
	if len(res) > 0 {
		var ids []any
		for _, v := range res {
			ids = append(ids, v.ID)
		}

		subEntitySettingMap := make(map[string]map[string]*model.ColumnSetting)
		if eagerLoadEntities, ok := eagerLoadMap[bannerEntityName]; ok {
			for _, entity := range eagerLoadEntities {
				if entity == "total" {
					_, total, err = l.svcCtx.Banner.GetList(l.ctx, model.M{}, 0, filterMap)
					if err != nil {
						total = 0
					}
					continue
				}

				if entitySettingMap, ok := model.RpcEntityPreloadMap[entity]; ok {
					subEntitySettingMap[entity] = entitySettingMap
				}
			}
		}

		idMediaMap := make(map[uint64][]*backend.MediaInfo)
		backendMediaEntityName := model.RpcEntityNames.BackendMedia
		backendMediaRepositoryName := model.RepositoryNames.BackendMedia
		if _, ok := subEntitySettingMap[backendMediaEntityName]; ok {
			subPreloadFields, hasSubPreloadFields := preloadMap[backendMediaEntityName]
			subColumnMap, hasSubColumnMap := model.RepositoryPreloadMap[backendMediaRepositoryName]
			if hasSubPreloadFields && hasSubColumnMap {
				var subSelectCols []string = modelx.ParseSelectColumns(subPreloadFields, subColumnMap)
				subSelectCols = append(subSelectCols, model.AttachmentRelationshipColumns.ObjectID)

				subFilterMap := make(map[string]map[string][]any)
				subFilterMap[model.AttachmentRelationshipColumns.ObjectID] = map[string][]any{
					"in": ids,
				}
				subFilterMap[model.AttachmentRelationshipColumns.ObjectType] = map[string][]any{
					"equalTo": {globalkey.AttachmentLogTypeBanner},
				}
				list, _, err := l.svcCtx.Banner.GetMedia(l.ctx, model.M{
					"orderBy": model.AttachmentRelationshipColumns.AttachmentOrder,
					"select":  strings.Join(subSelectCols, ","),
				}, -1, subFilterMap)
				if err != nil {
					return nil, err
				}

				if len(list) > 0 {
					for _, v := range list {
						idMediaMap[v.ObjectID] = append(idMediaMap[v.ObjectID], &backend.MediaInfo{
							Uid:       &v.RelationshipID,
							Id:        pointy.GetPointer(strconv.FormatInt(int64(v.AttachmentID), 10)),
							Thumbnail: pointy.GetPointer(uint32(v.AttachmentThumbnail)),
							Order:     pointy.GetPointer(uint32(v.AttachmentOrder)),
							Uri:       &v.AttachmentImageSource,
							Url:       &v.AttachmentImageURL,
							AltText:   &v.AttachmentImageAlt,
							MetaData:  &v.AttachmentImageMeta,
						})
					}
				}
			}
		}

		for _, v := range res {
			var newMedia []*backend.MediaInfo
			if media, ok := idMediaMap[v.ID]; ok {
				newMedia = media[:]
			}
			var sort *uint32
			if v.Sort != uint16(globalkey.SystemDefaultSort) {
				sort = pointy.GetPointer(uint32(v.Sort))
			}
			resp.List = append(resp.List, &backend.BannerInfo{
				Id:        &v.ID,
				PicUrl:    &v.PicURL,
				Type:      pointy.GetPointer(uint32(v.Type)),
				Title:     &v.Title,
				LinkType:  pointy.GetPointer(uint32(v.LinkType)),
				LinkUrl:   &v.LinkURL,
				AdType:    pointy.GetPointer(uint32(v.ObjectType)),
				AdId:      &v.ObjectID,
				Status:    pointy.GetPointer(uint32(v.Status)),
				Sort:      sort,
				CreatedAt: pointy.GetPointer(modelx.FormatTime(v.CreatedAt, "")),
				UpdatedAt: pointy.GetPointer(modelx.FormatTime(v.UpdatedAt, "")),
				DeletedAt: pointy.GetPointer(modelx.FormatNullDotTime(v.DeletedAt, "")),
				Media:     newMedia,
			})
		}
	}
	resp.Total = uint64(total)

	return resp, nil
}
